/*  ------------------------------------------------------------------------
	 NQ Common Services Library
	 
	 Homepage: http://www.awzhome.de/
	 ------------------------------------------------------------------------
	 
	 The contents of this file are subject to the Mozilla Public License
	 Version 1.1 (the "License"); you may not use this file except in
	 compliance with the License. You may obtain a copy of the License at
	 http://www.mozilla.org/MPL/
	 
	 Software distributed under the License is distributed on an "AS IS"
	 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	 License for the specific language governing rights and limitations
	 under the License.
	
	 The Original Code is code of NQ Common Services Library.

	 The Initial Developer of the Original Code is Andreas Weizel.
	 Portions created by the Initial Developer are
	 Copyright (C) 2006-2012 Andreas Weizel. All Rights Reserved.
	 
	 Contributor(s): (none)
	 
	 Alternatively, the contents of this file may be used under the terms
	 of the GNU General Public License Version 2.0 or later (the "GPL"),
	 or the GNU Lesser General Public License Version 2.1 or later (the
	 "LGPL"), in which case the provisions of the GPL or the LGPL are
	 applicable instead of those above. If you wish to allow use of your
	 version of this file only under the terms of the GPL or the LGPL and
	 not to allow others to use your version of this file under the MPL,
	 indicate your decision by deleting the provisions above and replace
	 them with the notice and other provisions required by the GPL or the
	 LGPL. If you do not delete the provisions above, a recipient may use
	 your version of this file under the terms of any of the MPL, the GPL
	 or the LGPL.
	 ------------------------------------------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Text;
using AWZhome.NQ.Core;
using AWZhome.NQ.Core.Fluent;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Windows.Data;

namespace AWZhome.NQ.CommonServices
{

	internal class NQBarBand : IBarBand
	{
		private ToolBar _toolBar = null;
		private ContextMenu _contextMenu = null;
		private Button _buttonAddRemove = null;
		private BarService _parentBarServ;
		private Style _contextMenuItemStyle = null;
		private Dictionary<string, NQBarItem> _itemList = new Dictionary<string, NQBarItem>();
		private string _bandKey;
		private string _displayName = String.Empty;
		private BarBandType _bandType;
		private bool _visible = false;
		private bool _hideAlways = false;
		private bool _showOverflowButton = true;
		private BandDockDirection _dockDirection = BandDockDirection.DockTop;

		private Thickness? _marginWithoutOverflowButton;
		private Thickness? _marginWithOverflowButton;

		private IResourceManager _servRes;

		internal NQBarBand(BarService parentBarServ, BarBandType bandType, string bandKey)
		{
			this._parentBarServ = parentBarServ;
			this._bandType = bandType;
			this._bandKey = bandKey;

			_contextMenuItemStyle = this.CreateMenuItemStyle();

			// Initialize services
			_servRes = ServiceCore
				.Get<Services.IResourceService>()
				.To;

			// Initialize the single ToolStrip
			switch (bandType)
			{
				case BarBandType.ToolBand:
					_toolBar = new ToolBar();

					// Setup the "Add/Remove buttons" overflow menu
					_buttonAddRemove = new Button();
					_buttonAddRemove.Click += _buttonAddRemove_Click;
					_buttonAddRemove.Content = _servRes.GetResString("NQCS", "Bar.mnuToolBarAddRemove");
					ToolBar.SetOverflowMode(_buttonAddRemove, OverflowMode.Always);
					_toolBar.Items.Add(_buttonAddRemove);

					// We can set the ShowOverflowButton property only after the control has been initialized
					// (as it accesses the template) -> we update the property in Loaded event
					_toolBar.Loaded +=
						delegate(object sender, RoutedEventArgs e)
						{
							this.ShowOverflowButton = _showOverflowButton;

							// Just a test
							//System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
							//settings.Indent = true;
							//using (System.Xml.XmlWriter xmlWriter =
							//   System.Xml.XmlWriter.Create(@"C:\Dokumente und Einstellungen\WheizAlien\Desktop\ToolBarTemplate_Luna.xml", settings))
							//{
							//   System.Windows.Markup.XamlWriter.Save(
							//     _toolBar.Template, xmlWriter);
							//}
						};

					break;

				case BarBandType.MenuBand:
					Menu innerMenu = new Menu();
					innerMenu.Background = Brushes.Transparent;

					_toolBar = new ToolBar();
					_toolBar.Items.Add(innerMenu);
					_toolBar.HorizontalAlignment = HorizontalAlignment.Stretch;
					_toolBar.Background = Brushes.Transparent;

					// We can set the ShowOverflowButton property only after the control has been initialized
					// (as it accesses the template)
					_toolBar.Loaded +=
						delegate(object sender, RoutedEventArgs e)
						{
							this.ShowOverflowButton = false;
							this.ShowGrip = false;
						};

					break;

				case BarBandType.ContextMenu:
					_contextMenu = new ContextMenu();
					TextOptions.SetTextFormattingMode(_contextMenu, TextFormattingMode.Display);
					_contextMenu.Resources.Add("", _contextMenuItemStyle);
					_contextMenu.Background = SystemColors.WindowBrush;

					break;
			}
		}

		#region INQBarBand members

		public BarBandType BandType
		{
			get
			{
				return _bandType;
			}
		}

		public void AddItem(string itemKey)
		{
			if (_parentBarServ.ItemExists(itemKey) && !this.ItemExists(itemKey))
			{
				// Add ToolStripItem to ToolStrip
				NQBarItem item = _parentBarServ._GetItem(itemKey);
				_itemList.Add(itemKey, item);

				MenuItem menuItem = item.ItemControl as MenuItem;
				if (menuItem != null)
				{
					menuItem.Style = _contextMenuItemStyle;
				}

				if (_bandType == BarBandType.ContextMenu)
				{
					_contextMenu.Items.Add(item.ItemControl);
				}
				else if (_bandType == BarBandType.MenuBand)
				{
					((Menu) _toolBar.Items.GetItemAt(0)).Items.Add(item.ItemControl);
				}
				else
				{
					_toolBar.Items.Add(item.ItemControl);
				}
			}
		}

		public void InsertItem(string itemKey, string neighborKey, bool insertBefore)
		{
			if (_parentBarServ.ItemExists(itemKey) && ((neighborKey == null) || _parentBarServ.ItemExists(neighborKey)) && !this.ItemExists(itemKey))
			{
				// Insert ToolStripItem before or after another specified ToolStripItem
				NQBarItem item = _parentBarServ._GetItem(itemKey);
				NQBarItem neighborItem = null;
				int newindex = 0;
				if (neighborKey == null)
				{
					newindex = 0;
				}
				else
				{
					neighborItem = _parentBarServ._GetItem(neighborKey);
					if (_bandType == BarBandType.ContextMenu)
					{
						newindex = _contextMenu.Items.IndexOf(neighborItem.ItemControl) + (insertBefore ? 0 : 1);
					}
					else if (_bandType == BarBandType.MenuBand)
					{
						newindex = ((Menu) _toolBar.Items.GetItemAt(0)).Items.IndexOf(neighborItem.ItemControl) + (insertBefore ? 0 : 1);
					}
					else
					{
						newindex = _toolBar.Items.IndexOf(neighborItem.ItemControl) + (insertBefore ? 0 : 1);
					}
				}

				_itemList.Add(itemKey, item);

				MenuItem menuItem = item.ItemControl as MenuItem;
				if (menuItem != null)
				{
					menuItem.Style = _contextMenuItemStyle;
				}

				if (_bandType == BarBandType.ContextMenu)
				{
					_contextMenu.Items.Insert(newindex, item.ItemControl);
				}
				else if (_bandType == BarBandType.MenuBand)
				{
					((Menu) _toolBar.Items.GetItemAt(0)).Items.Insert(newindex, item.ItemControl);
				}
				else
				{
					_toolBar.Items.Insert(newindex, item.ItemControl);
				}
			}
		}

		public void RemoveItem(string itemKey)
		{
			if (_parentBarServ.ItemExists(itemKey) && this.ItemExists(itemKey))
			{
				// Remove ToolStripItem from ToolStrip
				NQBarItem item = _parentBarServ._GetItem(itemKey);
				if (_bandType == BarBandType.ContextMenu)
				{
					_contextMenu.Items.Remove(item.ItemControl);
				}
				else if (_bandType == BarBandType.MenuBand)
				{
					((Menu) _toolBar.Items.GetItemAt(0)).Items.Remove(item.ItemControl);
				}
				else
				{
					_toolBar.Items.Remove(item.ItemControl);
				}

				_itemList.Remove(itemKey);
			}
		}

		public void ShowAsContextMenu(int x, int y)
		{
			if (this._bandType == BarBandType.ContextMenu)
			{
				_contextMenu.Placement = PlacementMode.Absolute;
				_contextMenu.PlacementRectangle = new Rect(x, y, 0, 0);
				_contextMenu.IsOpen = true;
			}
		}

		public bool ItemExists(string itemKey)
		{
			if (itemKey != null)
			{
				return _itemList.ContainsKey(itemKey);
			}
			else
			{
				return false;
			}
		}

		public string[] GetItemKeys()
		{
			string[] items = new string[_itemList.Keys.Count];
			_itemList.Keys.CopyTo(items, 0);
			return items;
		}

		public string BandKey
		{
			get
			{
				return _bandKey;
			}
		}

		public string DisplayName
		{
			get
			{
				return _displayName;
			}
			set
			{
				_displayName = value;

				// Set the title in band list
				if (_parentBarServ.ItemExists("mnuBandList." + _bandKey))
				{
					IBarItem listRoot = _parentBarServ.GetItem("mnuBandList." + _bandKey);
					listRoot.ItemText = _displayName;
				}
			}
		}

		public bool ShowGrip
		{
			get
			{
				if (_bandType == BarBandType.ToolBand)
				{
					return !ToolBarTray.GetIsLocked(_toolBar);
				}
				else
				{
					return false;
				}
			}
			set
			{
				if (_bandType == BarBandType.ToolBand)
				{
					ToolBarTray.SetIsLocked(_toolBar, !value);
				}
				else if (_bandType == BarBandType.MenuBand)
				{
					ToolBarTray.SetIsLocked(_toolBar, true);
				}
			}
		}

		public bool ShowOverflowButton
		{
			get
			{
				return _showOverflowButton;
			}
			set
			{
				if ((_bandType == BarBandType.ToolBand) || (_bandType == BarBandType.MenuBand))
				{
					// Show or hide the button in the ToolBar's template
					if (_toolBar.Template != null)
					{
						if (_bandType == BarBandType.MenuBand)
						{
							// A menu bar shouldn't have an overflow button
							value = false;
						}

						// Hide the OverflowGrid element in ToolBar's control template
						FrameworkElement toggleButton = _toolBar.Template.FindName("OverflowGrid", _toolBar) as FrameworkElement;
						if (toggleButton != null)
						{
							toggleButton.Visibility = (value) ? Visibility.Visible : Visibility.Collapsed;
						}

						// We have to patch the overflow button margin in ToolBar's control template
						FrameworkElement mainPanelBorder = _toolBar.Template.FindName("MainPanelBorder", _toolBar) as FrameworkElement;
						if (mainPanelBorder != null)
						{
							if (value)
							{
								// Original margin for the overflow button
								if (!_showOverflowButton && !_marginWithoutOverflowButton.HasValue)
								{
									_marginWithoutOverflowButton = new Thickness(
										mainPanelBorder.Margin.Left,
										mainPanelBorder.Margin.Top,
										mainPanelBorder.Margin.Left,
										mainPanelBorder.Margin.Bottom);
								}

								if (_marginWithOverflowButton.HasValue)
								{
									mainPanelBorder.Margin = _marginWithOverflowButton.Value;
								}
							}
							else
							{
								// No margin for overflow button
								if (_showOverflowButton && !_marginWithOverflowButton.HasValue)
								{
									_marginWithOverflowButton = mainPanelBorder.Margin;
								}

								if (!_marginWithoutOverflowButton.HasValue)
								{
									_marginWithoutOverflowButton = new Thickness(
										mainPanelBorder.Margin.Left,
										mainPanelBorder.Margin.Top,
										mainPanelBorder.Margin.Left,
										mainPanelBorder.Margin.Bottom);
								}

								if (_marginWithoutOverflowButton.HasValue)
								{
									mainPanelBorder.Margin = _marginWithoutOverflowButton.Value;
								}
							}
						}

						if (_buttonAddRemove != null)
						{
							_buttonAddRemove.Visibility =
									(value) ? Visibility.Visible : Visibility.Collapsed;
							ToolBar.SetOverflowMode(_buttonAddRemove,
								(_showOverflowButton) ? OverflowMode.Always : OverflowMode.Never);
						}

						_toolBar.UpdateLayout();
					}
				}
				_showOverflowButton = value;
			}
		}

		public bool BandVisible
		{
			get
			{
				return _visible;
			}
			set
			{
				if (((_bandType == BarBandType.ToolBand) || (_bandType == BarBandType.MenuBand)) && (_visible != value))
				{
					_visible = value;
					_parentBarServ.SetBandVisibility(this, value);
				}
			}
		}

		public bool HideAlways
		{
			get
			{
				return _hideAlways;
			}
			set
			{
				_hideAlways = value;
				// Update visibility
				if (_bandType == BarBandType.ToolBand)
				{
					_parentBarServ.SetBandVisibility(this, _visible);
					_parentBarServ.SetBandHiddenAlways(this, value);
				}
			}
		}

		public int BandLine
		{
			get
			{
				if (_bandType == BarBandType.ContextMenu)
				{
					return -1;
				}
				else
				{
					return _toolBar.BandIndex;
				}
			}
			set
			{
				if (_bandType != BarBandType.ContextMenu)
				{
					_toolBar.BandIndex = value;
				}
			}
		}

		public BandDockDirection DockDirection
		{
			get
			{
				return _dockDirection;
			}
			set
			{
				if (_dockDirection != value)
				{
					_dockDirection = value;
					if (_visible)
					{
						this.BandVisible = false;
						this.BandVisible = true;
					}
				}
			}
		}

		internal ToolBar ToolBar
		{
			get
			{
				return _toolBar;
			}
		}

		internal ContextMenu ContextMenu
		{
			get
			{
				return _contextMenu;
			}
		}

		#endregion

		private void _buttonAddRemove_Click(object sender, RoutedEventArgs e)
		{
			// Show "Add/Remove buttons" dialog
			(new Visual.BandCustomizeWindow(_parentBarServ, this)).ShowDialog();
		}

		private void toolStrip_ParentChanged(object sender, EventArgs e)
		{
			//if ((_bandType == NQBarBandType.ToolBand) || (_bandType == NQBarBandType.MenuBand))
			//{
			//  if (toolStrip.Parent != null)
			//  {
			//    // Update DockDirection property
			//    _dockDirection = _parentBarServ.DirectionFromToolStripPanel((ToolStripPanel) toolStrip.Parent);

			//    // Set toolstrip item orientation
			//    if ((_dockDirection == NQBandDockDirection.DockTop) || (_dockDirection == NQBandDockDirection.DockBottom))
			//    {
			//      toolStrip.TextDirection = ToolStripTextDirection.Horizontal;
			//    }
			//    else if ((_dockDirection == NQBandDockDirection.DockRight) || (_dockDirection == NQBandDockDirection.DockLeft))
			//    {
			//      toolStrip.TextDirection = ToolStripTextDirection.Vertical90;
			//    }
			//  }
			//}
		}

		private Style CreateMenuItemStyle()
		{
			ToolBar tempToolBar = new ToolBar();
			Menu tempMenu = new Menu();
			Style menuItemStyle = new Style(typeof(MenuItem));
			Style menuStyle = (Style) tempMenu.FindResource(ToolBar.MenuStyleKey);
			Style baseMenuItemStyle = (Style) menuStyle.Resources[typeof(MenuItem)];
			menuItemStyle.BasedOn = baseMenuItemStyle;

			return menuItemStyle;
		}
	}

}
